<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js_copy</title>
</head>
<body>
<script type="text/javascript">

    /**
     * 支持深浅拷贝
     * @param obj
     * @returns {*}
     */
    function cloneObj(obj){
        var str,
            newobj = obj.constructor === Array ? [] : {};

        if(typeof obj !== 'object'){
            throw new Error("you params is not a object! please enter a  object or array!");
        } else if(window.JSON){
            /**
             * JSON.stringify
             * JSON.parse
             * 方式
             *
             */
            console.log(">>>>use JSON.stringify to JSON.parse<<<<");
            str = JSON.stringify(obj), //系列化对象
                newobj = JSON.parse(str); //还原
        } else {
            /**
             * 递归方式
             */
            console.log(">>>>use recursion<<<<");
            for(var i in obj){
                newobj[i] = typeof obj[i] === 'object' ?
                                               cloneObj(obj[i]) : obj[i];
            }
        }
        return newobj;
    };

    //测试1.基本的数值
    //console.log(cloneObj(123));
    //测试2.数组
    //console.log(cloneObj([123,456,789]));
    //测试3 对象
    console.log(cloneObj([
          {
            id:1,
            name:'hsj',
            age:18,
            addrs:{
                addr1:'tangchi',
                addr2:'guanduqu'
            }
          },
        {
            id:2,
            name:'hsj_2',
            age:18,
            addrs:{
                addr1:'tangchi_2',
                addr2:'guanduqu_2'
            }
        },
        {
            id:3,
            name:'hsj_3',
            age:18,
            addrs:'guanduqu'
        }
        ]));
</script>
</body>
</html>